package com.chengyi.serialport.demo.gson

import android.os.Bundle
import com.google.gson.JsonObject
import com.google.gson.reflect.TypeToken
import com.hjq.gson.factory.GsonFactory


fun createVoid(): Void {
    val clz = Void::class.java
    val constructor = clz.getDeclaredConstructor()
    constructor.isAccessible = true
    val obj = constructor.newInstance()
    constructor.isAccessible = false
    return obj
}

inline fun <reified T> String.fromJson(): T? {
    return when (T::class.java) {
        Unit::class.java -> {
            Unit as? T
        }
        Void::class.java -> {
            createVoid() as? T
        }
        java.lang.String::class.java, String::class.java -> {
            this as? T
        }
        else -> {
            try {
                GsonFactory.getSingletonGson().fromJson<T>(this, object : TypeToken<T>() {}.type)
            } catch (e: Exception) {
                null
            }
        }
    }
}

fun Any.toJson(): String {
    if (this is String) {
        return this
    }
    return GsonFactory.getSingletonGson().toJson(this)
}

fun Any.toJsonObject() = this.toJson().fromJson<JsonObject>()
inline fun <reified T> Any.toObject(): T? = this.toJson().fromJson<T>()
inline fun <reified T> JsonObject.getAs(key: String): T? = this.get(key)?.toObject()
inline fun <reified T> Bundle.getAs(key: String): T? = this.get(key)?.toObject()
